package org.alvin.dispatchtcp;

import java.nio.ByteBuffer;

public class EndianConverter {

    // 将int转换为大端字节序
    public static byte[] toBigEndian(int value) {
        return ByteBuffer.allocate(4).putInt(value).array();
    }

    // 将int转换为小端字节序
    public static byte[] toLittleEndian(int value) {
        return new byte[]{
                (byte) (value & 0xFF),
                (byte) ((value >> 8) & 0xFF),
                (byte) ((value >> 16) & 0xFF),
                (byte) ((value >> 24) & 0xFF)
        };
    }

    // 将大端字节序转换为int
    public static int fromBigEndian(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getInt();
    }

    // 将小端字节序转换为int
    public static int fromLittleEndian(byte[] bytes) {
        return (bytes[0] & 0xFF) |
                ((bytes[1] & 0xFF) << 8) |
                ((bytes[2] & 0xFF) << 16) |
                ((bytes[3] & 0xFF) << 24);
    }

    public static void main(String[] args) {
        int value = 0x1A2B3C4D;

        // 转换为大端
        byte[] bigEndianBytes = toBigEndian(value);
        System.out.println("大端字节序: " + bytesToHex(bigEndianBytes));

        // 转换为小端
        byte[] littleEndianBytes = toLittleEndian(value);
        System.out.println("小端字节序: " + bytesToHex(littleEndianBytes));

        // 从大端转换回int
        int fromBigEndian = fromBigEndian(bigEndianBytes);
        System.out.println("从大端转换回int: " + Integer.toHexString(fromBigEndian));

        // 从小端转换回int
        int fromLittleEndian = fromLittleEndian(littleEndianBytes);
        System.out.println("从小端转换回int: " + Integer.toHexString(fromLittleEndian));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}